import { reqAddAddress, reqUpdateAddress, reqAddressInfo } from '@/api/address'
import Schema from 'async-validator'
Page({
  // 页面的初始数据
  data: {
    name: '', //收货人
    phone: '', //手机号码
    provinceName: '', //省
    provinceCode: '', //省编码
    cityName: '', //市
    cityCode: '', //市编码
    districtName: '', //区
    districtCode: '', //市编码
    address: '', //详细地址
    fullAddress: '', //完整地址
    isDefault: false
  },

  // 保存收货地址
  async saveAddrssForm(event) {
    const { provinceName, cityName, districtName, address, isDefault } = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }

    const { valid } = await this.validateAddress(params)
    if (!valid) return
    const res = this.addressId ? await reqUpdateAddress(params) : await reqAddAddress(params)
    if (res.code === 200) {
      wx.navigateBack()
      wx.toast({
        title: this.addressId ? '更改成功' : '保存成功'
      })
    }
    // wx.navigateBack()
  },

  // 验证表单
  validateAddress(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      name: [
        { pattern: nameRegExp, message: '请输入正确姓名' },
        { required: true, message: '姓名不能为空' }
      ],
      phone: [
        { required: true, message: '手机号码不能为空' },
        { pattern: phoneReg, message: '请输入正确手机号码' }
      ],
      provinceName: [{ required: true, message: '请输入所在地区' }],
      address: [{ required: true, message: '请输入详细地址' }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.toast({
            title: errors[0].message
          })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },

  // 省市区选择
  onAddressChange(event) {
    // console.log(event)
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode, cityCode, districtCode] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },

  // 更改信息
  async showAddressInfo(id) {
    // reqUpdateAddress(id)
    if (!id) return

    this.addressId = id

    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })
    const { data } = await reqAddressInfo(id)
    // console.log(res)
    this.setData(data)
  },
  onLoad(options) {
    // console.log()
    this.showAddressInfo(options.id)
  }
})
